package common;

/**
 * @author Q
 * @create 2025-07-12-15:13
 */

import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;

/**
 * 创建驱动对象
 */
public class Utils {
    public static WebDriver driver;
    public static WebDriver createDriver() {
        if(driver == null) {
            WebDriverManager.chromedriver().setup();
            ChromeOptions options = new ChromeOptions();
            //允许所有链接
            options.addArguments("--remote-allow-origins=*");
            //创建驱动对象
            driver = new ChromeDriver(options);
            //默认所有页面都等待2秒，防止访问太快报错(不作用弹窗)
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(2));
        }
        return driver;
    }
    public Utils(String url) {
        //调用driver对象
        driver = createDriver();
        //访问url（网址）
        driver.get(url);
    }

    /**
     * 屏幕截图
     * @param str
     * @throws IOException
     */
    public static void getScreenshot(String str) throws IOException {
        //设定格式
        SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sim2 = new SimpleDateFormat("HHmmssSS");
        //获取时间
        String dirTime = sim1.format(System.currentTimeMillis());
        String fileTime = sim2.format(System.currentTimeMillis());
        //目录
        String filename = "./src/test/image/" + dirTime + "/" + str + "-" + fileTime + ".png";
        File srcfile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        //把屏幕截图放到指定的路径下
        FileUtils.copyFile(srcfile,new File(filename));
    }
}
